﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Linq.Expressions;

namespace MIS
{
    public partial class register : Form
    {
        
        private login Login;
        public register(login login)
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            Login = login;
        }

        

        string strCon = @"data source=DESKTOP-4ULJ8AF;initial catalog = 'MIS';integrated security =true";

        /// <summary>
        /// 添加子菜单
        /// </summary>
        /// <param name="text">要显示的文字，如果为 - 则显示为分割线</param>
        /// <param name="cms">要添加到的子菜单集合</param>
        /// <param name="callback">点击时触发的事件</param>
        /// <returns>生成的子菜单，如果为分隔条则返回null</returns>

        ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback, string tag)
        {

            if (!string.IsNullOrEmpty(text))
            {

                ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
                tsmi.Tag = tag;
                if (callback != null) tsmi.Click += callback;
                cms.Add(tsmi);
                ToolStripSeparator tsp = new ToolStripSeparator();
                cms.Add(tsp);
                return tsmi;
            }


            return null;
        }
        void MenuClicked(object sender, EventArgs e)
        {
            dateTimePicker1.Value = DateTime.Now;
            ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem)sender;
            //MessageBox.Show(toolStripMenuItem.Tag.ToString());
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "select * from Doctor where Id='{0}'";
                strCmd = string.Format(strCmd, toolStripMenuItem.Tag.ToString());
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                string[] values2 = new string[ds.Tables[0].Columns.Count];
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    values2[i] = ds.Tables[0].Rows[0][i].ToString();
                }
                D_id.Text = values2[0];
                Dname.Text = values2[1];
                Dept_type.Text = values2[3];
                Dept.Text = values2[4];
                Dsex.Text = values2[5];
                Day_rq.Text = values2[6];
                Contact.Text = values2[7];
                Price_kind.Text = values2[8];

                comboBox1.Items.Clear();
                comboBox1.Text = null;
                    
                    string str = "select  Time from Schedule where Id='{0}' order by Id";
                    str = string.Format(str, D_id.Text);
                    SqlCommand command = new SqlCommand(str, con);
                    SqlDataReader dr = command.ExecuteReader();

                    while (dr.Read())
                    {
                        object[] values = new object[dr.FieldCount];
                    string[] time = new string[dr.FieldCount];
                    dr.GetValues(values);
                    dr.GetValues(time);
                    string []values1 = time[0].Split('-');
                    DateTime dt1 = Convert.ToDateTime(values1[0]);
                    DateTime dt2 = Convert.ToDateTime(values1[1]);

                        if (DateTime.Compare(dt2, DateTime.Now) > 0)
                        {
                            comboBox1.Items.AddRange(values);
                        }

                    }
                    dr.Close();

            }
            if (comboBox1.Items.Count==0)
            {
                State.Text = "无号";
                
            }
            else
            {
                State.Text = "可挂号";
                
            }
        }



        private void tabPage2_Click(object sender, EventArgs e)
        {

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void register_Load_1(object sender, EventArgs e)
        {
            this.Text = "诊疗卡号：" +Login.Tag;
            
         
            ToolStripMenuItem subItem;
            using (SqlConnection con = new SqlConnection(strCon))
            {

                con.Open();
                string strCmd = "select distinct Dept_type from Doctor";
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string values = ds.Tables[0].Rows[i][0].ToString();
                    subItem = AddContextMenu(values, menuStrip1.Items, null, null);
                    string str = "select distinct Dname,Id from Doctor where Dept_type='{0}'";
                    str = string.Format(str, values);

                    SqlDataAdapter da1 = new SqlDataAdapter(str, con);
                    DataSet ds1 = new DataSet();
                    da1.Fill(ds1);
                    for (int j = 0; j < ds1.Tables[0].Rows.Count; j++)
                    {
                        string values1 = ds1.Tables[0].Rows[j][0].ToString();
                        AddContextMenu(values1, subItem.DropDownItems, new EventHandler(MenuClicked), ds1.Tables[0].Rows[j][1].ToString());
                    }
                }

                string str1 = "select * from Patient where Card_num='{0}'";
                str1 = string.Format(str1,Login.Tag);
                SqlDataAdapter da2 = new SqlDataAdapter(str1, con);
                DataSet ds2 = new DataSet();
                da2.Fill(ds2);
                string[] values3 = new string[ds2.Tables[0].Columns.Count];
                for (int i = 0; i < ds2.Tables[0].Columns.Count; i++)
                {
                    values3[i] = ds2.Tables[0].Rows[0][i].ToString();
                }
                Pname.Text = values3[1];
                Psex.Text = values3[2];
                Page.Text = values3[3];
                Pphone.Text = values3[4];
                Id_type.Text = values3[5];
                Idnum.Text = values3[6];


            }


            string minDate = DateTime.Now.ToShortDateString().ToString();
            dateTimePicker1.MinDate = Convert.ToDateTime(minDate);
            string maxDate = DateTime.Now.AddDays(7).ToShortDateString().ToString();
            dateTimePicker1.MaxDate = Convert.ToDateTime(maxDate);

        }

        private void menuStrip1_MouseEnter(object sender, EventArgs e)
        {
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click_1(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(D_id.Text))
            {
                MessageBox.Show("请选择科室医生");
            }
            else if (string.IsNullOrEmpty(comboBox1.Text))
            {
                MessageBox.Show("请选择预约时间");
            }
            else
            {
                if (MessageBox.Show(Dname.Text + "医生\n" + dateTimePicker1.Value.ToShortDateString().ToString() + "\t" + comboBox1.Text + "\n确定预约吗？", "提示",
                 MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (SqlConnection con = new SqlConnection(strCon))
                    {
                        con.Open();
                        string strCmd = "select COUNT(*) from Reg";
                        SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        int count = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                        reg(count);
                        MessageBox.Show("挂号成功！");
                    }
                }
                else
                {
                    // Do something after the Yes button was clicked by user.
                }
            }
        }
        public void reg(int count)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "insert Reg values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";
                strCmd = string.Format(strCmd, ++count, Login.Tag, Pname.Text, Psex.Text, Dept_type.Text, Dept.Text, D_id.Text, Price_kind.Text, comboBox1.Text + " - "+ dateTimePicker1.Value.ToShortDateString().ToString(), "候诊");
                SqlCommand command = new SqlCommand(strCmd, con);
                command.ExecuteNonQuery();
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            comboBox1.Text = null;
                comboBox1.Items.Clear();
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    string str = "select  Time from Schedule where Id='{0}' order by Id";
                    str = string.Format(str, D_id.Text);
                    SqlCommand command = new SqlCommand(str, con);
                    SqlDataReader dr = command.ExecuteReader();

                    while (dr.Read())
                    {
                        object[] values = new object[dr.FieldCount];
                        dr.GetValues(values);
                    if (dateTimePicker1.Value.ToLongDateString().ToString() != DateTime.Now.ToLongDateString().ToString())
                    {
                        comboBox1.Items.AddRange(values);
                    }
                    else if (dateTimePicker1.Value.ToLongDateString().ToString() == DateTime.Now.ToLongDateString().ToString())
                    {
                        string[] time = new string[dr.FieldCount];
                        dr.GetValues(time);
                        string[] values1 = time[0].Split('-');
                        DateTime dt1 = Convert.ToDateTime(values1[0]);
                        DateTime dt2 = Convert.ToDateTime(values1[1]);

                        if (DateTime.Compare(dt2, DateTime.Now) > 0)
                        {
                            comboBox1.Items.AddRange(values);
                        }
                    } 
                    }
                dr.Close();
                }
            if (!string.IsNullOrEmpty(State.Text))
            {
                if (comboBox1.Items.Count == 0)
                {
                    State.Text = "无号";
                }
                else
                {
                    State.Text = "可挂号";
                }
            }
          
            
            
               
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Pname.Visible = false;
            Page.Visible = false;
            Psex.Visible = false;
            Page.Visible = false;
            Pphone.Visible = false;
            Id_type.Visible = false;
            Idnum.Visible = false;
            button2.Visible = false;

            xPname.Text = Pname.Text;
            xPsex.Text = Psex.Text;
            xPage.Text = Page.Text;
            xPphone.Text = Pphone.Text;
            xId_type.Text = Id_type.Text;
            xIdnum.Text = Idnum.Text;


            xPname.Visible = true;
            xPage.Visible = true;
            xPsex.Visible = true;
            xPage.Visible = true;
            xPphone.Visible = true;
            xId_type.Visible = true;
            xIdnum.Visible = true;
            button3.Visible = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("修改成功！");
            
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "update Patient  set Pname= '{0}', Psex ='{1}', Page = '{2}' ,Pphone='{3}',Idtype='{4}',Idnum='{5}' where Card_num = '{6}'";
                strCmd = string.Format(strCmd,xPname.Text,xPsex.Text,xPage.Text,xPphone.Text,xId_type.Text,xIdnum.Text,Login.Tag );
                SqlCommand command = new SqlCommand(strCmd, con);
                command.ExecuteNonQuery();

            }
            Pname.Text = xPname.Text;
            Psex.Text = xPsex.Text;
            Page.Text = xPage.Text;
            Pphone.Text = xPphone.Text;
            Id_type.Text = xId_type.Text;
            Idnum.Text = xIdnum.Text;


            button3.Visible = false;
            button2.Visible = true;

            xPname.Visible = false;
            xPage.Visible = false;
            xPsex.Visible = false;
            xPage.Visible = false;
            xPphone.Visible = false;
            xId_type.Visible = false;
            xIdnum.Visible = false;

            Pname.Visible = true;
            Page.Visible = true;
            Psex.Visible = true;
            Page.Visible = true;
            Pphone.Visible = true;
            Id_type.Visible = true;
            Idnum.Visible = true;


        }

        private void xPname_KeyPress(object sender, KeyPressEventArgs e)
        {
            Regex rg = new Regex("^[\u4e00-\u9fa5]+$"); //正则表达式

            if (!rg.IsMatch(e.KeyChar.ToString()) && e.KeyChar != '\b') //'\b'是退格键

            {

                e.Handled = true;

            }
        }

        private void xPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键 
            {
                int len = xPage.Text.Length;
                if (len < 1 && e.KeyChar == '0')
                {
                    e.Handled = true;
                }
                else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字 
                {
                    e.Handled = true;
                }
            }
        }

        private void xPphone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键 
            {
                int len = xPphone.Text.Length;
                if (len < 1 && e.KeyChar == '0')
                {
                    e.Handled = true;
                }
                else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字 
                {
                    e.Handled = true;
                }
            }
        }

        private void xIdnum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键 
            {
                int len = xIdnum.Text.Length;
                if (len < 1 && e.KeyChar == '0')
                {
                    e.Handled = true;
                }
                else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字 
                {
                    e.Handled = true;
                }
            }
        }

        private void Regstat_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage4)
            {
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                        string strCmd = "select Serial_num,Doctor.Dept_type,Doctor.Dept,Dname,Reg.Price_kind,Reg.Date,state from Doctor inner join Reg on Doctor.Id= Reg.Id where Card_num='{0}' and (State='就诊'or state='候诊')";
                        strCmd = string.Format(strCmd, Login.Tag);
                        SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        Regstat.DataSource = ds.Tables[0].DefaultView;
                    Regstat.Columns[0].HeaderCell.Value = "病历号";
                    Regstat.Columns[1].HeaderCell.Value = "科室";
                    Regstat.Columns[2].HeaderCell.Value = "科室号";
                    Regstat.Columns[3].HeaderCell.Value = "挂号医生";
                    Regstat.Columns[4].HeaderCell.Value = "挂号费";
                    Regstat.Columns[5].HeaderCell.Value = "预约时间";
                    Regstat.Columns[6].HeaderCell.Value = "状态";
                }
            }
            if (tabControl1.SelectedTab == tabPage3)
            {
                
            }
        }

        private void label17_Click(object sender, EventArgs e)
        {

        }



        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd;
                if (choose.Text == "就诊")
                {
                    strCmd = "select Serial_num,Doctor.Dept_type,Doctor.Dept,Dname,Reg.Price_kind,Reg.Date,state from Doctor inner join Reg on Doctor.Id= Reg.Id where Card_num='{0}' and State='就诊'";
                }
                else if (choose.Text == "候诊")
                {
                    strCmd = "select Serial_num,Doctor.Dept_type,Doctor.Dept,Dname,Reg.Price_kind,Reg.Date,state from Doctor inner join Reg on Doctor.Id= Reg.Id where Card_num='{0}' and State='候诊'";
                }
                else
                {
                    strCmd = "select Serial_num,Doctor.Dept_type,Doctor.Dept,Dname,Reg.Price_kind,Reg.Date,state from Doctor inner join Reg on Doctor.Id= Reg.Id where Card_num='{0}' order by Serial_num desc";
                }
                strCmd = string.Format(strCmd, Login.Tag);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                Regstat.DataSource = ds.Tables[0].DefaultView;
                Regstat.Columns[0].HeaderCell.Value = "病历号";
                Regstat.Columns[1].HeaderCell.Value = "科室";
                Regstat.Columns[2].HeaderCell.Value = "科室号";
                Regstat.Columns[3].HeaderCell.Value = "挂号医生";
                Regstat.Columns[4].HeaderCell.Value = "挂号费";
                Regstat.Columns[5].HeaderCell.Value = "预约时间";
                Regstat.Columns[6].HeaderCell.Value = "状态";
            }
        }

        private void Regstat_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string Serial_num = Regstat.CurrentRow.Cells["Serial_num"].Value.ToString();
                string State = Regstat.CurrentRow.Cells["State"].Value.ToString();
                if (State == "候诊")
                {
                    cancel.Enabled = true;
                }

                if (State == "完成就诊")
                {
                    search.Enabled = true;
                }

                Serialnum.Text = Serial_num;
                xState.Text = State;
            }
            catch (System.NullReferenceException)
            {

            }
           
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("病历号："+Serialnum.Text+ "\n确定取消挂号吗？", "提示",
                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    string strCmd = "delete from Reg where Serial_num='{0}' and Card_num='{1}'";
                    strCmd = string.Format(strCmd, Serialnum.Text,Login.Tag);
                    SqlCommand command = new SqlCommand(strCmd, con);
                    command.ExecuteNonQuery();
                    init();
                }
            }
            else
            {
                // Do something after the Yes button was clicked by user.
            }
        }
        public  void init()
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "select Serial_num,Doctor.Dept_type,Doctor.Dept,Dname,Reg.Price_kind,Reg.Date,state from Doctor inner join Reg on Doctor.Id= Reg.Id where Card_num='{0}' and (State='就诊'or state='候诊')";
                strCmd = string.Format(strCmd, Login.Tag);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                Regstat.DataSource = ds.Tables[0].DefaultView;
                Regstat.Columns[0].HeaderCell.Value = "病历号";
                Regstat.Columns[1].HeaderCell.Value = "科室";
                Regstat.Columns[2].HeaderCell.Value = "科室号";
                Regstat.Columns[3].HeaderCell.Value = "挂号医生";
                Regstat.Columns[4].HeaderCell.Value = "挂号费";
                Regstat.Columns[5].HeaderCell.Value = "预约时间";
                Regstat.Columns[6].HeaderCell.Value = "状态";
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabPage3;
            sSerial_num.Text =Serialnum.Text;
            
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "select Dept_type,Dept,Date,Past,Exam,Sult,Now,Pri_diag,Aux_diag,Orders from EMR where Serial_num='{0}'";
                strCmd = string.Format(strCmd, sSerial_num.Text);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                int m = da.Fill(ds);
                if (m != 0)
                {
                    string[] values = new string[ds.Tables[0].Columns.Count];
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        values[i] = ds.Tables[0].Rows[0][i].ToString();
                    }
                    sDept_type.Text = values[0];
                    sDept.Text = values[1];
                    sDate.Text = values[2];
                    Past.Text = values[3];
                    Exam.Text = values[4];
                    Sult.Text = values[5];
                    Now.Text = values[6];
                    Pri_diag.Text = values[7];
                    Aux_diag.Text = values[8];
                    Orders.Text = values[9];

                    string str = "select Drug_name,Drug_num,Drug_price from Reci where Serial_num='{0}'";
                    str = string.Format(str, sSerial_num.Text);
                    SqlDataAdapter da1 = new SqlDataAdapter(str, con);
                    DataSet ds1 = new DataSet();
                    da1.Fill(ds1);
                    Reci.DataSource = ds1.Tables[0].DefaultView;
                    Reci.Columns[0].HeaderCell.Value = "药品名称";
                    Reci.Columns[1].HeaderCell.Value = "药品数量";
                    Reci.Columns[2].HeaderCell.Value = "药品价格";
                }


            }
        }

        private void label33_Click(object sender, EventArgs e)
        {

        }

        private void label33_Click_1(object sender, EventArgs e)
        {

        }

        private void label32_Click(object sender, EventArgs e)
        {

        }

        private void Past_TextChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string strCmd = "select Dept_type,Dept,Date,Past,Exam,Sult,Now,Pri_diag,Aux_diag,Orders from EMR where Serial_num='{0}' and Card_num='{1}'";
                strCmd = string.Format(strCmd, searchtext.Text,Login.Tag);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                int m = da.Fill(ds);
                if (m != 0)
                {
                    string[] values = new string[ds.Tables[0].Columns.Count];
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        values[i] = ds.Tables[0].Rows[0][i].ToString();
                    }
                    sSerial_num.Text = searchtext.Text;
                    sDept_type.Text = values[0];
                    sDept.Text = values[1];
                    sDate.Text = values[2];
                    Past.Text = values[3];
                    Exam.Text = values[4];
                    Sult.Text = values[5];
                    Now.Text = values[6];
                    Pri_diag.Text = values[7];
                    Aux_diag.Text = values[8];
                    Orders.Text = values[9];


                    string str = "select Drug_name,Drug_num,Drug_price from Reci where Serial_num='{0}'";
                    str = string.Format(str, sSerial_num.Text);
                    SqlDataAdapter da1 = new SqlDataAdapter(str, con);
                    DataSet ds1 = new DataSet();
                    da1.Fill(ds1);
                    Reci.DataSource = ds1.Tables[0].DefaultView;
                    Reci.Columns[0].HeaderCell.Value = "药品名称";
                    Reci.Columns[1].HeaderCell.Value = "药品数量";
                    Reci.Columns[2].HeaderCell.Value = "药品价格";
                }
                else
                {
                    MessageBox.Show("病历号不存在！");
                }


            }
        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }
    }
}
